<?php

namespace app\enterprise\controller;
use app\enterprise\model\course\Course as CourseModel;
use app\enterprise\model\course\Courseware;
use app\enterprise\model\course\CourseLinkWare;
use app\enterprise\model\TrainType as TrainTypeModel;
use app\enterprise\service\DataType;
use think\exception\ValidateException;

class Course extends Enterprise
{


    public function list()
    {

        $create_type = input('create_type', '');

        $page = input('page', 1);
        $size = input('size', 10);
        $course_name = input('course_name', '');
        $type_ids = input('type_ids', []);
        $start_time = strtotime(input('start_time', ''));
        $end_time = strtotime(input('end_time', ''));
        $exclude_ids = input('exclude_ids', []);
        $course_type = input('course_type', '');
        $require_type = input('require_type', '');
        $userIds = userIds($this->adminId);
        $where = [];

//        $where[] = ['creator_id', 'in', $userIds];
        $where[] = [ 'status','=',1];

        // 公共资源
        $resource_type = input('resource_type', '');
//        $is_my_resource = input('is_my_resource', '');
        if ( !empty($resource_type) ) {


            if ( $resource_type == 1 || $resource_type == 2 ) {
                $where[] = [ 'resource_type','=', $resource_type ];
            } else if ( $resource_type == 3 ) {
                // 只查我的
                $where[] = ['creator_id', '=', $userIds];
                $where[] = [ 'resource_type','=', $resource_type ];

                // 我的资源, 包含公共的, 平台的, 我的
//                if ( !empty($is_my_resource) ) {
//                    // 只查我的资源
//                    $where[] = ['creator_id', 'in', $userIds];
//                    $where[] = [ 'resource_type','=', $resource_type ];
//                } else {
//                    // 我的资源, 包含公共的, 平台的, 我的
//                    $where[] = [ 'resource_type','in', '1,2,3' ];
//                }
            }
        }

        $data = CourseModel::order('id', 'desc')
            ->when(!empty($exclude_ids), function ($query) use ($exclude_ids) {
                $query->whereNotIn('id', $exclude_ids);
            })
            ->when($course_name, function ($query) use ($course_name) {
                $query->where('course_name', 'like', '%' . $course_name . '%');
            })
            ->when($course_type, function ($query) use ($course_type) {
                $query->where('course_type', $course_type);
            })
            ->when($require_type, function ($query) use ($require_type) {
                $query->where('require_type', $require_type);
            })
            ->where(function ($query) use ($type_ids) {
                if (!empty($type_ids)) {
                    foreach ($type_ids as $typeId) {
                        $query->whereOr('type_ids', 'like', '%,' . $typeId . ',%');
                    }
                }
            })
            ->when($start_time, function ($query) use ($start_time) {
                $query->where('create_time', '>=', $start_time);
            })
            ->when($end_time, function ($query) use ($end_time) {
                $query->where('create_time', '<=', $end_time);
            })
//            ->where(function ($query) use ($create_type) {
//
//                if (empty($create_type)) {
//                    $query->where('company_id', $this->adminId)->whereOr('company_id', 0);
//                } else if ($create_type == 1) {
//                    $query->where('company_id', 0);
//                } else if ( $create_type == 3 ){
//                    $query->where('resource_type', 1);
//                } else {
//                    $query->where('company_id', $this->adminId);
//                }
//            })
            ->where($where)
            ->paginate($size)
            ->each(function ($item) {

                $ware_ids = json_decode($item->ware_json);
                $courseware_duration = 0;
                if (!empty($ware_ids)) {
                    $courseware_duration =  Courseware::where('id', 'in', $ware_ids)->sum('duration');
                }
                $item->ware_duration = $courseware_duration;
                $item->ware_count = $ware_ids ? count($ware_ids) : 0;

                if ($item['type_ids']) {
                    $typeIds = explode(',', $item['type_ids'] ?? '');
                    $types = TrainTypeModel::whereIn('id', $typeIds)
                        ->column('title');
                    $item->type_name = implode(',', $types);
                } else {
                    $item->type_name = '';
                }
            });

//            $list = $data->items();
//            $del_total_num = 0;
//            // 如果是 我的资源, 需要筛选出来 自己的 删除的数据量
//            if ( $resource_type == 3 && empty($is_my_resource) ) {
//                foreach ($list as $key => &$value) {
//                    if ( $value['resource_type'] == 3 && $value['creator_id'] != $this->adminId ) {
//                        unset($list[$key]);
//                        $del_total_num += 1;
//                    }
//                }
//            }

            return app('json')->success([
                'list' => $data->items(),
                'total' => $data->total(),
                'total_page'=>$data->lastPage(),
            ]);

    }

    public function save()
    {

        $company_id = $this->adminId;

        $data = $this->request->only([
            'course_name', 'type_ids', 'merchant_type_id', 'img_url', 'desc',  'require_type', 'course_type'
            ]);

        $ware_ids = array_unique(input('ware_ids', []));


        try {
            validate([
                'type_ids|培训类型' => 'require|array',
                'course_name|课程名称' => 'require|max:255',
//                'merchant_type_id|企业类型' => 'require|number',
//                'img_url|课程图片' => 'require|max:255',
                'desc|课程介绍' => 'require|max:255',
                'course_type|课程类型' => 'require|number|in:1,2',
                'require_type|选修类型' => 'require|number|in:1,2',
            ])->check($data);

            $id = input('id', '');

            $data['type_ids'] = ','.implode(',', $data['type_ids']).',';
            if (!$id) {
                $data['company_id'] = $company_id;
                $data['ware_json'] = json_encode($ware_ids);
                // 是否是公共资源
                $resource_type = input('resource_type', '');
                if ( !empty($resource_type)  )  {
                    $data['resource_type'] = $resource_type;
                }
                $data['creator_id'] = $this->adminId;
                $res = CourseModel::create($data);
                $id = $res->id;

                if (!empty($ware_ids)) {
                    $insert_data = [];
                    foreach ($ware_ids as $ware_id) {
                        $insert_data[] = [
                            'course_id' => $id,
                            'courseware_id' => $ware_id,
                            'status' => 1
                        ];
                    }
                    CourseLinkWare::insertAll($insert_data);
                }

            } else {
                $one = CourseModel::getOne($id);

                if (!$one) {
                    return app('json')->fail('要操作的数据不存在');
                }

                if ($one['company_id'] != $this->adminId) {
                    return app('json')->fail('您没有权限操作该数据');
                }

                $data['ware_json'] = json_encode($ware_ids);

                $res = CourseModel::update($data, ['id' => $id]);

                CourseLinkWare::arrayDelete(['course_id'=>$id]);

                if (!empty($ware_ids)) {
                    $insert_data = [];
                    foreach ($ware_ids as $ware_id) {
                        $insert_data[] = [
                            'course_id' => $id,
                            'courseware_id' => $ware_id,
                            'status' => 1
                        ];
                    }
                    CourseLinkWare::insertAll($insert_data);
                }

            }
            return app('json')->success();
        } catch (ValidateException $exception) {
            return app('json')->fail($exception->getMessage());
        }
    }

    public function delete()
    {
        $id = input('id', '');
        if (empty($id)) {
            return app('json')->fail('请选择要删除的数据');
        }

        CourseModel::arrayDelete(['id'=>$id, 'company_id'=>$this->adminId]);

        return app('json')->success();

    }

    public function selectCourseWares()
    {
        $id = input('id', '');
        $page = input('page', 1);
        $size = input('size', 10);

        if (empty($id)) {
            return app('json')->fail('请选择要查询的课程');
        }

        $query = CourseLinkWare::hasWhere('courseware', function ($q) use ($id) {
            $q->where('status', 1);
        });
        $data = $query->where('CourseLinkWare.status','=', 1)->where('course_id', $id)->order('id asc, courseware_id asc')

//            ->paginate($size);
            ->select();

//        $items = $data->items();
        $items = $data;

        $wares = [];

        $all_ware_ids = [];

        foreach ($items as $item) {
            $ware = $item->courseware;
            $type_ids = $item->courseware->type_ids;
            if ($type_ids) {
                $typeIds = explode(',', $type_ids ?? '');
                $types = TrainTypeModel::whereIn('id', $typeIds)
                    ->column('title');
                $ware['type_name'] = implode(',', $types);
            }
            $wares[] = $ware;
            $all_ware_ids[] = $ware['id'];
        }

//        $all_ware_ids = CourseLinkWare::where('course_id', $id)->where('status', 1)->column('courseware_id');

        return app('json')->success([
            'list' => $wares,
//            'total' => $data->total(),
//            'total_page'=>$data->lastPage(),
            'all_ware_ids'=>$all_ware_ids
        ]);

    }

    public function info()
    {
        $id = input('id', '');
        if (empty($id)) {
            return app('json')->fail('请选择要查询的课程');
        }

        $data = CourseModel::getOne($id);

        try {
            $trainTypeRelates = DataType::getTrainTypeRelates($data['type_ids']);
            $data['selected_type_ids'] = $trainTypeRelates['id_chains'];

            $data['type_names'] =  '-';
            if (!empty($trainTypeRelates['title_chains'])) {
                $data['type_names'] = implode('/', array_map(function ($item) {
                    return implode('-', $item);
                }, $trainTypeRelates['title_chains']));
            }

            $data['type_ids'] = explode(',', trim($data['type_ids'], ','));


        } catch (\Exception $e) {
            $data['type_ids'] = [];
        }

        return app('json')->success([
            'data' => $data
        ]);
    }





}